package com.asking.service;

import com.asking.dao.CollectionMapper;
import com.asking.domain.Collection;
import com.asking.domain.Question;
import com.asking.pojo.EsQuestion;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CollectionService {
    @Resource
    private CollectionMapper collectionMapper;
    @Resource
    private QuestionService questionService;

    /**
     * 添加收藏
     * @param uid
     * @param qid
     */
    public void addCollection(String uid, String qid) {
        Collection collection = new Collection();
        collection.setUid(Integer.parseInt(uid));
        collection.setQid(Integer.parseInt(qid));
        collectionMapper.insert(collection);
    }

    /**
     * 移除收藏
     *
     * @param uid
     * @param qid
     */
    public void deleteCollection(String uid, String qid) {
        Collection collection = new Collection();
        collection.setUid(Integer.parseInt(uid));
        collection.setQid(Integer.parseInt(qid));
        collectionMapper.delete(collection);
    }

    /**
     * 获取该用户收藏的问题
     *
     * @param userId
     * @return
     */
    public PageInfo<EsQuestion> findQuestion(String userId) {
        Example example = new Example(Collection.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uid", userId);
        List<Collection> collections = collectionMapper.selectByExample(example);
        List<EsQuestion> esQuestions = new ArrayList<>();
        for (Collection collection : collections) {
            EsQuestion esQuestion = questionService.selectByAnswer(collection.getQid());
            esQuestions.add(esQuestion);
        }
        return new PageInfo<>(esQuestions);
    }
}
